{% extends '_base_list.html' %}

{% block title %}
    用户管理
{% endblock %}


{% block top_css %}
    {{ super() }}
    <!--bees-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bees.css') }}">
{% endblock %}


<!-- Content head -->
{% block head_title %}
    系统管理
{% endblock %}
{% block head_nav %}
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-home"></i></a></li>
        <li><a href="#">权限管理</a></li>
        <li class="active">用户管理</li>
    </ol>
{% endblock %}


<!-- Content body -->
{% block title_filter %}
    <div class="filter">
        <div class="row">
            <div class="col-xs-12 col-sm-2">
                <div class="form-group">
                    <input type="text" class="form-control" name="create_time" placeholder="请选择日期日期" autocomplete="off">
                </div>
            </div>
            <div class="col-xs-6 col-sm-2">
                <div class="form-group">
                    <select class="select2 form-control" name="role" data-placeholder="角色">
                    </select>
                </div>
            </div>
            <div class="col-xs-6 col-sm-2">
                <div class="form-group">
                    <select class="select2 form-control" name="is_dimission" data-placeholder="是否离职">
                        <option value=""></option>
                        <option value="0">离职</option>
                        <option value="1">正常</option>
                    </select>
                </div>
            </div>
            <div class="col-xs-12 col-sm-3 pull-right">
                <div class="form-group">
                    <div class="input-group">
                        <input type="text" name="search" placeholder="请输入姓名或工号" class="form-control">
                        <span class="input-group-btn">
                            <button name="search" class="btn btn-mint" type="button">
                                <i class="fa fa-search"></i>
                            </button>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block body_operator %}
    <div class="operator mar-btm">
        <div class="row">
            <div class="col-xs-12 text-center">
                {% if current_user.has_perm('users-user-create') %}
                    <button class="btn btn-primary btn-sm" id="add"><i class=""></i> 新增用户</button>
                {% endif %}
                {% if current_user.has_perm('users-user-update') %}
                    <button class="btn btn-mint btn-sm" id="edit"><i class=""></i> 修改用户</button>
                {% endif %}
                {% if current_user.has_perm('users-user-delete') %}
                    <button class="btn btn-danger btn-sm" id="del"><i class=""></i> 删除用户</button>
                {% endif %}
                {% if current_user.has_perm('users-user-password') %}
                    <button class="btn btn-purple btn-sm" id="pwd"><i class=""></i> 密码重置</button>
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}

{% block body_table %}
    <table id="userTable" class="table table-auto"></table>
{% endblock %}


{% block buttom_js %}
    {{ super() }}
    <!--bees-->
    <script src="{{ url_for('static', filename='js/bees.js') }}"></script>

    <script type="text/javascript">

        $(function () {
            bees.initSelect2();
            bees.initServerSideSelect2(
                $('select[name="role"]'),
                {url: '{{ url_for('perms.api-role-list') }}'}
            );
            bees.initDaterangepicker($('input[name="create_time"]'),{
                opens: "right",
                timePicker: false,
                timePickerSeconds: false,
                singleDatePicker: false,
                locale: {
                    format: 'YYYY-MM-DD'
                }
            });

            // 回填和初始化默认过滤参数
            var createTimeEle = $("input[name='create_time']");
            var roleEle = $("select[name='role']");
            var isDimissionEle = $("select[name='is_dimission']");
            var searchEle = $('input[name="search"]');

            var filterParams = JSON.parse(window.sessionStorage.getItem("filterParams"));
            if(filterParams){
                // 回填表单过滤条件
                createTimeEle.val(filterParams.create_time);
                // roleEle.val(filterParams.role).trigger("change");
                // select2通过ajax加载的数据必须使用下面的数据回显方式
                bees.select2DataEcho(
                    roleEle,
                    {
                        url: '{{ url_for('perms.api-role-list') }}',
                        selected: [filterParams.role],
                        async: false    // 只能通过同步的方式
                    }
                );
                isDimissionEle.val(filterParams.is_dimission).trigger("change");
                searchEle.val(filterParams.search);
                window.sessionStorage.removeItem("filterParams");
            }else {
                // 默认表单过滤条件
                filterParams = {
                    'create_time': createTimeEle.val(),
                    'role': roleEle.val(),
                    'is_dimission': isDimissionEle.val(),
                    'search': searchEle.val()
                };
            }
            $.fn.beesTable.defaultFilterParams(filterParams);

            // 初始化表格
            var $tableEle = $("#userTable");
            var options = {
                columns: [
                    {title: '选择', field: 'selected', radio: true},
                    {title: '姓名', field: 'name', sortable: false},
                    {title: '用户', field: 'username', sortable: false},
                    {title: '邮箱', field: 'email', sortable: false},
                    {title: '手机', field: 'phone', sortable: false},
                    {title: '角色', field: 'roles', sortable: false},
                    {title: 'MFA', field: 'otp_level', sortable: false,
                        formatter: function (value, row, index, field) {
                            // value: 字段值; row: 行记录数据; index: 行索引 ;field: 行字段
                            if(value === 0){
                                return '<span class="text text-danger text-bold">关闭</span>'
                            }
                            else if(value === 1){
                                return '<span class="text text-warning text-bold">开启</span>'
                            }
                            else if(value === 2){
                                return '<span class="text text-success text-bold">强制</span>'
                            }
                        }
                    },
                    {title: '超级管理员', field: 'is_admin', sortable: false,
                        formatter: function (value, row, index, field) {
                            // value: 字段值; row: 行记录数据; index: 行索引 ;field: 行字段
                            if(value === 0){
                                return '<span class="text text-danger text-bold">否</span>'
                            }else{
                                return '<span class="text text-success text-bold">是</span>'
                            }
                        }
                    },
                    {title: '是否离职', field: 'is_dimission', sortable: false,
                        formatter: function (value, row, index, field) {
                            // value: 字段值; row: 行记录数据; index: 行索引 ;field: 行字段
                            if(value === 0){
                                return '<span class="text-danger text-bold">离职</span>'
                            }else{
                                return '<span class="text-success text-bold">正常</span>'
                            }
                        }
                    },
                    {title: '登录IP', field: 'last_ip', sortable: false},
                    {title: '登录时间', field: 'last_login', sortable: true},
                    {title: '创建时间', field: 'create_time', sortable: true}
                ],
                url:'{{ url_for("users.api-user-list") }}',
                sortName: 'create_time',
                sortOrder: 'desc'
            };
            var table = $tableEle.beesTable(options);


            // 搜索
            bees.bindTableSearch({
                table: $tableEle,
                searches: [
                    {eventType:'change', eventSource:createTimeEle, data:function () {
                            return {'create_time': createTimeEle.val()};
                        }
                    },
                    {eventType:'change', eventSource:roleEle, data: function () {
                            return {'role': roleEle.select2("val")}
                        }
                    },
                    {eventType:'change', eventSource:isDimissionEle, data: function () {
                            return {'is_dimission': isDimissionEle.select2("val")}
                        }
                    },
                    {eventType:'click', eventSource:$('button[name="search"]'), data: function () {
                            return {'search': searchEle.val()}
                        }
                    }
                ]
            });

            // 操作
            bees.bindTableOperator({
                table: $tableEle,
                operator: {
                    add: {
                        href: '{{ url_for('users.user-create') }}'
                    },
                    show: {
                        disable: true
                    },
                    edit: {
                        href: '{{ url_for('users.user-update', pk=default_pk) }}'
                    },
                    del: {
                        confirmCallback: function (data) {
                            setAjaxCSRFToken();
                            $.ajax({
                                type: 'post',
                                url: '{{ url_for("users.user-delete", pk=default_pk) }}'.replace(bees.defaultPK, data.id),
                                data : {},
                                success: function (result) {
                                    if (result.code != 200) {
                                        bees.tipError({
                                            message: result.data.message
                                        });
                                    }else {
                                       bees.tipSuccess({
                                            message: "删除成功"
                                        });
                                    }

                                    //reload
                                    table.bt.bootstrapTable('refresh');
                                }
                            })
                        }
                    }
                }
            });

            // 重置密码
            $("#pwd").on('click', function () {
                var rows = $tableEle.bootstrapTable('getSelections');
                var data = rows[0];
                var count = rows.length;
                if(!count){
                    bees.tipWaring({
                        message: '请选择需要重置密码的用户'
                    });
                    return
                }

                bees.confirmBox({
                    title: '重置密码确认',
                    content: '您确定要重置改用户的密码？',
                    confirmCallback: function () {
                        setAjaxCSRFToken();
                        $.ajax({
                            type: 'post',
                            url: '{{ url_for("users.user-password-reset", pk=default_pk) }}'.replace(bees.defaultPK, data.id),
                            data : {},
                            success: function (result) {
                                if (result.code != 200) {
                                    bees.tipError({
                                        message: result.data.message
                                    });
                                }else {
                                   bees.tipSuccess({
                                        message: "密码已重置"
                                    });
                                }

                                //reload
                                table.bt.bootstrapTable('refresh');
                            }
                        })
                    }
                })
            })

        })
    </script>
{% endblock %}
